﻿using BW.WMS.ApiReulst;
using MD5Hash;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace BW.WMS.Login
{
    public class LoginService : ApplicationService, ILoginService
    {
        private readonly IRepository<User, Guid> _userRepository;
        private readonly IRepository<Role, Guid> _roleRepository;

        public LoginService(IRepository<User, Guid> userRepository, IRepository<Role, Guid> roleRepository)
        {
            _userRepository = userRepository;
            _roleRepository = roleRepository;
        }

        public async Task<ApiResult<LoginDTO>> Login(string name, string pwd)
        {
            var dto = new LoginDTO();
            var pwdMd5 = pwd.GetMD5();
            var user = await _userRepository.FirstOrDefaultAsync(u => u.UserName == name && u.UserPwd == pwdMd5);
            if (user == null)
            {
                return new ApiResult<LoginDTO>
                {
                    Code = LoginApiResult.Fail,
                    Message = "用户名或密码错误"
                };
            }
            var role = await _roleRepository.FirstOrDefaultAsync(r => r.Id.Equals(user.RoleID));
            dto.UserName = user.UserName;
            dto.RoleName = role.RoleName;
            dto. UserName = name;
            return new ApiResult<LoginDTO>
            {
                Code = LoginApiResult.Success,
                Data = dto
            };
        }
    }
}
